import {CALL_API, isRSAA} from 'redux-api-middleware'
import {modalTip} from 'nmbc/ModalTip'

export default store => next => action => {
    /**
     * redux-api-middleware 处理异常后，会抛出 ApiError 的错误，并在 action 上追加一个 error = true
     * 所以优先判断 action 中是否有 error 标识
     * 话说。。。。ram 你就应该把原始的 action 丢出来！两头都不好处理
     */
    if (action.error === true) {
        modalTip.error({
            message: action.payload.message,
            name: action.payload.name,
            code: action.payload.status || 0
        });
    }

    /** 处理并不是 ram 截获处理的 action */
    if (action.payload === undefined ||
        action.payload.action === undefined || action.payload.res === undefined ||
        (!isRSAA(action.payload.action))
    )
        return next(action);

    /**
     * 在服务器返回200时
     */
    try {
        const rsaa = action.payload.action;
        const res = action.payload.res;
        const callAPI = rsaa[CALL_API];
        const {types} = callAPI;
        let [requestType, successType, failureType] = types;

        const contentType = res.headers.get('Content-Type');
        if (contentType && ~contentType.indexOf('json')) {
            res.json().then((json) => {
                if (!json.result) {
                    action.payload = json;
                    action.type = (typeof failureType === 'object') ? failureType.type : failureType;
                    action.error = true;
                    modalTip.error({
                        message: json.userData.message,
                        name: json.userData.name,
                        code: json.userData.code
                    });
                } else {
                    action.payload = json.userData;
                }
                next(action);
            });
        } else {
            next(action);
        }
    } catch (e) {
        next(action);
    }
};
